package com.xixi.canal.client.starter.service;

import com.xixi.canal.client.starter.common.SyncSwitch;
import com.xixi.canal.client.starter.config.CanalConfig;
import com.xixi.canal.client.starter.config.SpringContext;
import com.xixi.canal.client.starter.loader.CanalClientStarter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Component
@RefreshScope
public class CanalClientService {

    private static final Logger logger = LoggerFactory.getLogger(CanalClientService.class);

    @Resource
    private ContextRefresher contextRefresher;

    @Resource
    private Environment env;

    @Resource
    private SyncSwitch syncSwitch;

    private volatile boolean running = false;


    private CanalClientStarter clientStarter;

    // 注入bean保证优先注册
    @Resource
    private SpringContext springContext;

    @Resource
    private CanalConfig canalConfig;

    @PostConstruct
    public synchronized void init() {

        if (running) return;

        try {

            logger.info("## start the canal client.");

            clientStarter = new CanalClientStarter(canalConfig);

            clientStarter.start();

            running = true;
            logger.info("## the canal client is running now ......");
        } catch (Exception e) {
            logger.error("## start canal client failed.reason:{}", e);
        }
    }


    @PreDestroy
    public synchronized void destroy() {
        if (!running) return;

        try {
            logger.info("## stop the canal client.");

            running = false;

            if (null != clientStarter) {
                clientStarter.stop();
            }

        } catch (Exception e) {
            logger.error("## stop canal client failed.reason:{}", e);
        } finally {
            logger.info("## the canal client is shutdown.");
        }
    }

    public synchronized void refresh(String destination, String fileName) {
        clientStarter.refresh(destination, fileName);
    }
}
